import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/bottom_navigation/botton_navigation_widget.dart';
import 'package:flutter_member/routes/application.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'course_card.dart';

// listView首位
int first;
// listView末位
int last;

class CourseTutorial extends StatefulWidget {
  final String mainTitle; //大標題
  final String subtitle; // 小標題
  final List<dynamic> listTuitionService;
  final String path; //跳轉路徑
  final bool isId; //是否传递id
  final Color mainColor;
  final Color subColor;
  final num mainTitleSize;

  const CourseTutorial(
      {Key key,
      this.mainTitle,
      this.listTuitionService,
      this.path,
      this.isId = false,
      this.subtitle,
      this.mainColor,
      this.subColor,
      this.mainTitleSize})
      : super(key: key);

  @override
  _CourseTutorialState createState() => _CourseTutorialState();
}

class _CourseTutorialState extends State<CourseTutorial> {
//  List<TuitionService> _serviceList = [];

//  ListView 控制器
  var _controller = ScrollController();
  var _ieItsControllerIndex;

//
  var widgetWidth = 160;

  get _listTuitionService => widget.listTuitionService;

//  跳轉頁面路徑
  get _path => widget.path;

//  點擊card 是否傳遞id
  get _isId => widget.isId;

//  大標題
  get _mainTitle => widget.mainTitle;

//  小標題
  get _subtitle => widget.subtitle;

//
  get _mainTitleSize => widget.mainTitleSize;
  Color color;
  String urls =
      "https://macauscholar.demo.ourmi.biz/api/files/macauscholar/rc-upload-1603765340039-2.jpeg";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  void dispose() {
    super.dispose();
    _controller.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: <Widget>[
          titleWidget(
              mainTitle: _mainTitle,
              mainColor: widget.mainColor,
              subColor: widget.subColor,
              subtitle: _subtitle),
          Container(
            height: ScreenUtil().setHeight(175),
            width: MediaQuery.of(context).size.width,
            child: EasyRefresh(
              header: PhoenixHeader(),
              footer: PhoenixFooter(),
              child: listViewLayoutCustom(widget.listTuitionService),
            ),
          )
        ],
      ),
    );
  }

  /// listView custom 构建
  Widget listViewLayoutCustom(_serviceList) {
    return ListView.custom(
      itemExtent: ScreenUtil().setHeight(125),
//      controller: _controller,
      scrollDirection: Axis.horizontal,
      childrenDelegate: MyChildrenDelegate(
        (BuildContext context, int index) {
          return AnimatedContainer(
            curve: Curves.easeOut,
            duration: Duration(microseconds: 400),
            child: CourseTutorialCard(
              title: _serviceList[index]['title'],
              objectId: _serviceList[index]['objectId'],
              bl: _serviceList[index]['blView'],
              description: _serviceList[index]['title'],
              color: Colors.amberAccent,
              src: _serviceList[index]['src'],
              titleColor: _serviceList[index]['titleColor'],
              onPressed: () {
                if (_isId == true) {
                  print(_serviceList[index]['objectId']);
                  Application.jump(
                      context, _path + "/${_serviceList[index]['objectId']}");
                } else {
                  Application.jump(context, _path);
                }

                setState(() {
                  for (int i = 0; i < _serviceList.length; i++) {
                    setState(() {
                      if (i == index) {
                        _serviceList[index]['blView'] = true;
                      } else {
                        _serviceList[i]['blView'] = false;
                      }
                    });
                  }
                });
              },
            ),
          );
        },
        childCount: _serviceList.length,
      ),
      cacheExtent: 0.0,
    );
  }

  Widget titleWidget(
      {@required String mainTitle,
      String subtitle,
      Color mainColor,
      Color subColor}) {
    return Container(
      width: ScreenUtil().setWidth(330),
      height: ScreenUtil().setHeight(36),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Column(
            children: <Widget>[
              Text(
                mainTitle,
                style: TextStyle(
                    color: mainColor,
                    fontSize: ScreenUtil().setSp(_mainTitleSize ?? 28),
                    fontWeight: FontWeight.w500),
              ),
              subtitle == null
                  ? Container()
                  : Text(
                      subtitle,
                      style: TextStyle(
                        color: subColor,
                        fontSize: ScreenUtil().setSp(12),
                      ),
                    )
            ],
          ),
          //跳轉到補習
          GestureDetector(
            onTap: () {
              Navigator.of(context).pushAndRemoveUntil(
                  MaterialPageRoute(
                      builder: (context) => BottomNavigationWidget(
                            indexState: 1,
                          )),
                  (route) => route == null);
            },
            child: ImageIcon(
              AssetImage('images/more.png'),
              size: 40,
              color: Color(0Xff9B9B9B),
            ),
          ),
        ],
      ),
    );
  }
}

typedef firstIndex = void Function(num);
typedef lastIndex = void Function(num);

// 监听listView列表中可见item第一位和最后一位
class MyChildrenDelegate extends SliverChildBuilderDelegate {
  MyChildrenDelegate(
    Widget Function(BuildContext, int) builder, {
    int childCount,
    bool addAutomaticKeepAlive = true,
    bool addRepaintBoundaries = true,
  }) : super(builder,
            childCount: childCount,
            addAutomaticKeepAlives: addAutomaticKeepAlive,
            addRepaintBoundaries: addRepaintBoundaries);

  ///监听 在可见的列表中 显示的第一个位置和最后一个位置
  @override
  void didFinishLayout(int firstIndex, int lastIndex) {
    first = firstIndex;
    last = lastIndex;
//    print('----$first-----$last');
//    print('firstIndex: $firstIndex, lastIndex: $lastIndex');
  }

  ///可不重写 重写不能为null  默认是true  添加进来的实例与之前的实例是否相同 相同返回true 反之false
  ///listView 暂时没有看到应用场景 源码中使用在 SliverFillViewport 中
  @override
  bool shouldRebuild(SliverChildBuilderDelegate oldDelegate) {
    // TODO: implement shouldRebuild
    print("oldDelegate$oldDelegate");
    return super.shouldRebuild(oldDelegate);
  }
}
